﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace RookieLibSharp.Security
{
    /// <summary>
    /// 软件升级信息类
    /// </summary>
    public class SoftwareUpdateInfor
    {
        /// <summary>
        /// 是否需要升级
        /// </summary>
        public bool NeedUpdate { get; protected set; }
        /// <summary>
        /// 升级版本号
        /// </summary>
        public Version UpdateVersion { get; protected set; }
        public Version CurrentVersion { get; protected set; }
        /// <summary>
        /// 升级网址
        /// </summary>
        public string UpdateUrl { get; protected set; }
        /// <summary>
        /// 升级信息所在的网址
        /// </summary>
        public string InfoUrl{get;protected set;}
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="infoUrl">升级信息所在网址</param>
        /// <param name="curVersion">当前版本号</param>
        public SoftwareUpdateInfor(string infoUrl, Version curVersion)
        {
            CurrentVersion = curVersion;
            InfoUrl = infoUrl;
            try
            {
                GetInfo();
            }
            catch
            {
                NeedUpdate = false;
            }
        }
        private void GetInfo()
        {
            Uri httpURL = new Uri(InfoUrl);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
            httpReq.Accept = "text/html, application/xhtml+xml, image/jxr, */*";
            httpReq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko";
            httpReq.Referer = httpURL.AbsoluteUri.Replace(httpURL.LocalPath, "");
            httpReq.Host = httpURL.Host;
            httpReq.KeepAlive = true;
            string str;
            HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
            using (Stream respStream = httpResp.GetResponseStream())
            {
                using (StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8))
                {
                    str = respStreamReader.ReadToEnd();
                    respStreamReader.Close();
                    respStream.Close();
                }
            }
            string strVer = LibFunction.GetMatchStr(str, @"(?<=<p>Version:V)(\d+.){3}\d+");
            if (strVer != "")
            {
                UpdateVersion = new Version(strVer);
            }
            UpdateUrl = LibFunction.GetMatchStr(str, "(?<=Download:<a href=\").+?(?=\")");
            NeedUpdate = UpdateVersion > CurrentVersion;
        }
    }
}
